//
//  SWUserAccountViewModel.swift
//  MYSwiftWeiBo
//
//  Created by shingwai chan on 16/2/28.
//  Copyright © 2016年 ChanShingWai. All rights reserved.
//

import UIKit

class SWUserAccountViewModel: NSObject {
    
    //单例
    static var sharedInstance: SWUserAccountViewModel = SWUserAccountViewModel()
    //用户账户模型模型
    var userAccount :SWUserAccount?
    //判断用户是否登陆
    var userLogin :Bool {
        get {
            return userAccount != nil
        }
    }
    
    //MARK: -- 第一次加载单例时 就读取userAccount
    private override init() {
        super.init()
        userAccount = loadUserAccount()
    }
    
    
    
    //MARK: -- 向新浪发送用户授权的 code 获取AssesToken
    func loadAccessToken(code: String, assTockenfinishedCallBack:(error: NSError?) ->()) {
        //利用netWork工具发送code到新浪服务器 获取 AssesscToken
        SWNetWorkTool.sharedNetWorkTool.laodAccessToken(code, assTokenFinished: { (reponse, eror) -> () in
            
            if  reponse == nil || eror != nil {
                //请求Token失败的话就调用闭包告诉控制器
                assTockenfinishedCallBack(error: eror)
                return
            }
            else{
                //从SWNetWorkTool工具里获得reponse字典
                print("请求Token成功:\(reponse)")
                //字典转模型
                self.userAccount = SWUserAccount(dict: reponse!)
                //把模型存到沙盒归档
                self.saveUserAccount()
                //获取token成功告诉控制器
                assTockenfinishedCallBack(error: nil) // ->传空就是成功
            }
        })
    }
    
    ///沙盒保存路径
    let accountPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last!.stringByAppendingString("/Account.plist")
    /**
      归档
    */
    func saveUserAccount() {
        if userAccount != nil {
            
            print("\(accountPath)")
            //选择要保持的模型
            NSKeyedArchiver.archiveRootObject(userAccount!, toFile: accountPath)
        }
    }
    
    
    //MARK: -- 将用户的UserAccount从沙盒读取
    func loadUserAccount() -> SWUserAccount? {
        //从沙盒读取模型
        let account = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? SWUserAccount
        
    // 账号日期:account?.expiresDate? 比:compare 现在日期:NSDate() 降序:NSComparisonResult.OrderedDescending
        //当账号能从沙盒读出来 并且授权日期比现在日期要大 为真
        if account != nil && account?.expiresDate?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
            print("用户授权日期\(account?.expiresDate)")
            return account
         
        }else{
            //nil是未登录
            print("未登录")
            return nil
        }
    }
    
    /**
     读取用户头像和名字
     - parameter loadUserInfoCallback: 传nil为读取成功
     */
    func loadUserInfo(loadUserInfoCallback: (error:  NSError?) -> () ) {
    
        SWNetWorkTool.sharedNetWorkTool.loadUserInfo { (result, error) -> () in
            if error != nil {
                //获取用户数据失败
                loadUserInfoCallback(error: error)
                return
            }
            
            //获取成功
            self.userAccount?.avatar_large = result?["avatar_large"] as? String
            self.userAccount?.screen_name = result?["screen_name"] as? String
            self.saveUserAccount()
            //执行闭包
            loadUserInfoCallback(error: nil)
        }
    }
}
